package cn.chiship.framework.upms.biz.system.controller;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.base.service.CacheService;
import cn.chiship.framework.upms.biz.system.entity.UpmsDataDict;
import cn.chiship.framework.upms.biz.system.entity.UpmsDataDictExample;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsDataDictDto;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsDataDictItemDto;
import cn.chiship.framework.upms.biz.system.service.UpmsDataDictService;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.base.constants.CacheConstants;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.pojo.vo.DataDictItemVo;
import cn.chiship.sdk.framework.util.FrameworkUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * UpmsDataDictController
 * 2021/9/27
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/dataDict")
@Api(tags = "数据字典")
public class UpmsDataDictController extends BaseController<UpmsDataDict, UpmsDataDictExample> {

    @Resource
    private UpmsDataDictService upmsDataDictService;

    @Resource
    private RedisService redisService;
    @Resource
    CacheService cacheService;

    @Override
    public BaseService getService() {
        return upmsDataDictService;
    }

    @ApiOperation(value = "字典组列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isNationalStandard", value = "标准(0:非标准 1:标准)", dataTypeClass = Byte.class, paramType = "query"),
    })
    @GetMapping(value = "list")
    public ResponseEntity<BaseResult> list(@RequestParam(required = false, defaultValue = "0", value = "isNationalStandard") Byte isNationalStandard) {
        UpmsDataDictExample upmsDataDictExample = new UpmsDataDictExample();
        upmsDataDictExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andIsNationalStandardEqualTo(isNationalStandard).andPidEqualTo("0");
        upmsDataDictExample.setOrderByClause(FrameworkUtil.formatSort("-gmtModified"));
        List<UpmsDataDict> dataDicts = upmsDataDictService.selectByExample(upmsDataDictExample);

        return super.responseEntity(BaseResult.ok(dataDicts));
    }

    @SystemOptionAnnotation(describe = "保存数据字典组", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "保存数据字典组")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsDataDictDto upmsDataDictDto) {
        UpmsDataDict upmsDataDict = new UpmsDataDict();
        BeanUtils.copyProperties(upmsDataDictDto, upmsDataDict);
        upmsDataDict.setPid("0");
        return super.responseEntity(super.save(upmsDataDict));
    }

    @SystemOptionAnnotation(describe = "更新数据字典组", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiOperation(value = "更新数据字典组")
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsDataDictDto upmsDataDictDto) {
        UpmsDataDict upmsDataDict = new UpmsDataDict();
        BeanUtils.copyProperties(upmsDataDictDto, upmsDataDict);
        upmsDataDict.setPid("0");
        return super.responseEntity(super.update(id, upmsDataDict));
    }

    @SystemOptionAnnotation(describe = "字典组数据项分页")
    @ApiOperation(value = "字典组数据项分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "pid", value = "所属字典组", required = true, dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "dataDictName", value = "字典名称", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/item/page")
    public ResponseEntity<BaseResult> dataDictItemPage(
            @RequestParam(value = "pid") String pid,
            @RequestParam(required = false, defaultValue = "", value = "dataDictName") String dataDictName) {
        UpmsDataDictExample upmsDataDictExample = new UpmsDataDictExample();
        UpmsDataDictExample.Criteria criteria = upmsDataDictExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO);
        criteria.andPidEqualTo(pid);
        if (!StringUtil.isNullOrEmpty(dataDictName)) {
            criteria.andDataDictNameLike("%" + dataDictName + "%");
        }
        return super.responseEntity(BaseResult.ok(super.page(upmsDataDictExample)));
    }

    @SystemOptionAnnotation(describe = "新增字典组数据项", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "新增字典组数据项")
    @PostMapping(value = "item/save")
    public ResponseEntity<BaseResult> dataDictItemSave(@RequestBody @Valid UpmsDataDictItemDto upmsDataDictItemDto) {
        UpmsDataDict upmsDataDict = new UpmsDataDict();
        BeanUtils.copyProperties(upmsDataDictItemDto, upmsDataDict);
        return super.responseEntity(super.save(upmsDataDict));
    }

    @SystemOptionAnnotation(describe = "新增字典组数据项", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),
    })
    @ApiOperation(value = "更新字典组数据项")
    @PostMapping(value = "item/update/{id}")
    public ResponseEntity<BaseResult> dataDictItemUpdate(@PathVariable("id") String id, @RequestBody @Valid UpmsDataDictItemDto upmsDataDictItemDto) {
        UpmsDataDict upmsDataDict = new UpmsDataDict();
        BeanUtils.copyProperties(upmsDataDictItemDto, upmsDataDict);
        upmsDataDict.setId(id);
        return super.responseEntity(super.update(id, upmsDataDict));
    }

    @ApiOperation(value = "根据字典组编号获取数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataDictCode", value = "字典组编号", required = true, dataTypeClass = String.class, paramType = "query")
    })
    @GetMapping(value = "getDataDictByCode")
    public BaseResult getDataDictByCode(@RequestParam(value = "dataDictCode") String dataDictCode) {
        UpmsDataDictExample upmsDataDictExample = new UpmsDataDictExample();
        upmsDataDictExample.createCriteria()
                .andIsDeletedEqualTo(BaseConstants.NO)
                .andDataDictCodeEqualTo(dataDictCode);
        List<UpmsDataDict> upmsDataDicts = upmsDataDictService.selectByExample(upmsDataDictExample);
        return BaseResult.ok(upmsDataDicts.isEmpty() ? null : upmsDataDicts.get(0));
    }

    @ApiOperation(value = "根据字典组编号获取数据字典数据(Redis获取)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataDictCode", value = "字典组编号", required = true, dataTypeClass = String.class, paramType = "query")
    })
    @GetMapping(value = "findByCode")
    public BaseResult findByCode(@RequestParam(value = "dataDictCode") String dataDictCode) {
        String dataDictItemKey = CommonCacheConstants.buildKey(CacheConstants.REDIS_DATA_DICT_ITEM_PREFIX);
        List<DataDictItemVo> dataDictItemVos = new ArrayList<>();

        List<UpmsDataDict> dataDictItems = (List<UpmsDataDict>) redisService.hget(dataDictItemKey, dataDictCode);
        if (!StringUtil.isNull(dataDictItems)) {
            dataDictItems.forEach(upmsDataDictItem -> {
                DataDictItemVo dataDictItemVo = new DataDictItemVo();
                dataDictItemVo.setId(upmsDataDictItem.getId());
                dataDictItemVo.setDataDictId(upmsDataDictItem.getPid());
                dataDictItemVo.setDataDictItemCode(upmsDataDictItem.getDataDictCode());
                dataDictItemVo.setDataDictItemName(upmsDataDictItem.getDataDictName());
                dataDictItemVo.setColorValue(upmsDataDictItem.getColorValue());
                dataDictItemVos.add(dataDictItemVo);
            });
        }
        return BaseResult.ok(dataDictItemVos);
    }

    @SystemOptionAnnotation(describe = "缓存数据字典组", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "缓存数据字典组")
    @GetMapping(value = "/cacheDataDict")
    public ResponseEntity<BaseResult> cacheDataDict() {
        cacheService.cacheDataDict();
        return super.responseEntity(BaseResult.ok());
    }


    @SystemOptionAnnotation(describe = "删除数据字典", option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE)
    @ApiOperation(value = "删除数据字典")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        UpmsDataDictExample upmsDataDictExample = new UpmsDataDictExample();
        upmsDataDictExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(upmsDataDictExample));
    }

}
